package com.pocketsweet;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.GetCallback;
import com.easemob.chat.EMContactManager;
import com.easemob.exceptions.EaseMobException;
import com.pocketsweet.chatui.Constant;
import com.pocketsweet.model.MLArticleLike;
import com.pocketsweet.model.MLOrder;
import com.pocketsweet.model.MLTestOrder;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.model.MLUserLike;
import com.pocketsweet.service.UserService;
import com.pocketsweet.utils.ACache;

public class MLCache {
	private static MLCache _self;
	private static Context _ctx;
	private static ACache _cache;
	private static int friendMultiple = 0;// 好友数量是1000的倍数
	private static int testOrderMultiple = 0;// 试聊数量是1000的倍数
	private static int LovePeopleMultiple = 0;// 点赞数量是1000的倍数
	private static int LoveArticleMultiple = 0;// 点赞数量是1000的倍数
	private static boolean isFriendOver1000 = false;// 好友数量是否超过1000条
	private static boolean isTestOrderOver1000 = false;// 试聊数量是否超过1000条
	private static boolean isLoveOver1000 = false;// 点赞数量是否超过1000条
	private static boolean isLoveArticleOver1000 = false;// 点赞数量是否超过1000条
	private String userIds = "";
	private String temp = "";

	public MLCache() {
	}

	public MLCache(Context context) {
		_cache = ACache.get(context);
		_ctx = context;
	}

	public static void init(Context context) {
		_self = new MLCache(context);
	}

	public static ACache getCache() {
		return _cache;
	}

	// 登录的时候获取好友信息保存user到本地
	public void InitUser() {

		// 获取好友
		AVQuery<MLUser> followeeQuery = MLUser.followeeQuery(
				UserService.getCurrentUserId(), MLUser.class);
		followeeQuery.include("followee");
		followeeQuery.setLimit(1000);
		followeeQuery.setSkip(friendMultiple * 1000);// 忽略前1000个
		followeeQuery.findInBackground(new FindCallback<MLUser>() {

			@Override
			public void done(List<MLUser> users, AVException e) {
				if (e == null) {

					if (users.size() > 0) {
						if (users.size() >= 1000) {// 当好友超过1000
							friendMultiple++;
							isFriendOver1000 = true;// 超过1000
						} else {
							isFriendOver1000 = false;
						}

						// try {
						for (MLUser mluser : users) {
							_cache.put(mluser.getObjectId(),
									mluser.toJSONObject());
							userIds += mluser.getObjectId() + ",";
						}

						// // 添加user"申请与通知"
						// JSONObject applyUser = new JSONObject();
						// applyUser.put("objectId",
						// Constant.NEW_FRIENDS_USERNAME);
						// applyUser
						// .put("nickName",
						// _ctx.getResources()
						// .getString(
						// R.string.Application_and_notify));
						// usertemp.put(Constant.NEW_FRIENDS_USERNAME,
						// applyUser);
						// // 添加"群聊"
						// JSONObject qunUser = new JSONObject();
						// qunUser.put("objectId", Constant.GROUP_USERNAME);
						// qunUser.put("nickName", _ctx.getResources()
						// .getString(R.string.group_chat));
						// _cache.put(Constant.GROUP_USERNAME, qunUser);
						//
						// // 添加 user”系统“
						// JSONObject sysUser = new JSONObject();
						// sysUser.put("objectId", Constant.SYSTEM);
						// sysUser.put("nickName", "口袋君");
						// _cache.put(Constant.SYSTEM, sysUser);
						//
						// // 添加 user”新的喜欢的人“
						// JSONObject likeUser = new JSONObject();
						// likeUser.put("objectId", Constant.NEW_LIKER);
						// likeUser.put("nickName", "喜欢");
						// _cache.put(Constant.NEW_LIKER, likeUser);
						// } catch (JSONException e1) {
						// // TODO Auto-generated catch block
						// e1.printStackTrace();
						// }

					}
					if (isFriendOver1000 == false) {// 当好友数量不超过1000时，即最后一次执行获取好友，执行一下代码
						// 保存好友id
						_cache.put("Friend_" + UserService.getCurrentUserId(),
								userIds);
						// 保存聊过天的人的Id
						_cache.put("Chat_" + UserService.getCurrentUserId(),
								userIds);
						_cache.put(UserService.getCurrentUserId(), UserService
								.getCurrentUser().toJSONObject());
						// 获取黑名单列表
						List<String> blackList;
						try {
							blackList = EMContactManager.getInstance()
									.getBlackListUsernamesFromServer();
							// 保存黑名单
							EMContactManager.getInstance().saveBlackList(
									blackList);
						} catch (EaseMobException e1) {
							e1.printStackTrace();
						}
						InitTestUser();// 获取试聊
					} else {
						InitUser();
					}
				}
			}
		});
	}

	// 判断是否是在聊天的人
	public static boolean isInChat(String userId) {
		String id = UserService.getCurrentUserId();
		if (_cache.getAsString("Chat_" + id) != null) {
			String[] ids = _cache.getAsString("Chat_" + id).split(",");
			for (int i = 0; i < ids.length; i++) {
				if (ids[i].equals(userId)) {
					return true;
				}
			}

		}
		return false;
	}

	public void InitTestUser() {
		// 获取试聊
		AVQuery<MLTestOrder> query = new AVQuery<MLTestOrder>("MLTestOrder");
		query.setLimit(1000);
		query.setSkip(testOrderMultiple * 1000);// 忽略前1000个
		query.whereEqualTo("sponsor", UserService.getCurrentUser());
		query.findInBackground(new FindCallback<MLTestOrder>() {

			@Override
			public void done(List<MLTestOrder> orders, AVException e) {
				if (e == null) {
					if (orders.size() >= 0) {
						if (orders.size() >= 1000) {// 当超过1000
							testOrderMultiple++;
							isTestOrderOver1000 = true;// 超过1000
						} else {
							isTestOrderOver1000 = false;
						}
						for (int i = 0; i < orders.size(); i++) {
							temp += orders.get(i).getWinner().getObjectId()
									+ ",";

						}
						if (isTestOrderOver1000 == false) {
							_cache.put(
									"TestOrder_"
											+ UserService.getCurrentUserId(),
									temp);
						} else {
							InitTestUser();
						}
					}
					// saveFriendToTestOrder();
				} else {
					// Log.e("==error", "error:" +
					// e.getMessage());

				}
			}

		});
	}

	public void getUserLike() {// 获取点赞的人
		final AVQuery<MLUserLike> query = new AVQuery<MLUserLike>("MLUserLike");
		query.include("likeUser");
		query.setLimit(1000);
		query.setSkip(LovePeopleMultiple * 1000);// 忽略前1000个
		query.whereEqualTo("user", UserService.getCurrentUser());
		query.findInBackground(new FindCallback<MLUserLike>() {
			@Override
			public void done(List<MLUserLike> list, AVException arg1) {
				if (arg1 == null) {
					if (list.size() > 0) {
						if (list.size() >= 1000) {// 当超过1000
							LovePeopleMultiple++;
							isLoveOver1000 = true;// 超过1000
						} else {
							isLoveOver1000 = false;
						}
						for (MLUserLike tempUser : list) {
							MLUserLike tempMLLike = tempUser;
							MLContext.saveUserLikeID(tempMLLike.getLikeUser()
									.getObjectId());
							MLContext.saveLike(MLContext.LIKE_TYPE_USER,
									tempMLLike.getLikeUser().getObjectId()
											.toString());
						}
						if (isLoveOver1000 == true) {
							getUserLike();
						}
					} else {
						if (LovePeopleMultiple == 0) {
							MLContext.getInstance().setUserLikeSizeZero();
						}
					}
				} else {
					// Log.e("＝＝错误", "查询点赞错误: " + arg1.getMessage());

				}

			}
		});
	}

	public void getArticleLike() {// 获取点赞的文章

		final AVQuery<MLArticleLike> query = new AVQuery<MLArticleLike>(
				"MLArticleLike");
		query.include("Article");
		query.setLimit(1000);
		query.setSkip(LoveArticleMultiple * 1000);// 忽略前1000个
		query.whereEqualTo("user", UserService.getCurrentUser());
		// query.include("Article");
		query.findInBackground(new FindCallback<MLArticleLike>() {
			@Override
			public void done(List<MLArticleLike> list, AVException arg1) {
				if (arg1 == null) {
					if (list.size() > 0) {
						// Log.e("====未保存", "查询到点赞" + list.size()
						// + " 条符合条件的数据");
						if (list.size() >= 1000) {// 当超过1000
							LoveArticleMultiple++;
							isLoveArticleOver1000 = true;// 超过1000
						} else {
							isLoveArticleOver1000 = false;
						}
						for (MLArticleLike tempUser : list) {
							MLContext.saveArticleLikeID(tempUser.getArticle()
									.getObjectId());
							MLContext.saveLike(MLContext.LIKE_TYPE_RECOMMEND,
									tempUser.getArticle().getObjectId()
											.toString());
						}
						if (isLoveArticleOver1000 == true) {
							getArticleLike();
						}
					} else {
						if (LoveArticleMultiple == 0) {
							MLContext.getInstance().setAticleLikeSizeZero();
						}
					}
				} else {
					// Log.e("＝＝错误", "查询点赞错误: " + arg1.getMessage());

				}

			}
		});
	}

	public static void saveFriendToTestOrder() {// 把主动聊天的好友都加入试聊列表
		// TODO Auto-generated method stub
		// 获取试聊
		AVQuery<MLOrder> query = new AVQuery<MLOrder>("MLOrder");
		query.limit(1000);
		query.whereEqualTo("sponsor", UserService.getCurrentUser());
		query.findInBackground(new FindCallback<MLOrder>() {

			@Override
			public void done(List<MLOrder> orders, AVException e) {
				if (e == null) {
					if (orders.size() != 0) {
						String userId = "";
						for (int i = 0; i < orders.size(); i++) {
							userId = orders.get(i).getWinner().getObjectId();
							if (!isHasTestOrder(userId)) {
								saveTestOrderUserId(userId);
							}
						}
					}
				} else {
					// Log.e("==error", "error:" + e.getMessage());

				}
			}

		});

	}

	// 保存一个好友
	public static void saveFriend(MLUser user) {
		String id = UserService.getCurrentUserId();
		String temp = _cache.getAsString("Friend_" + id) == null ? "" : _cache
				.getAsString("Friend_" + id);
		_cache.put("Friend_" + id, temp + user.getObjectId() + ",");
		_cache.put(user.getObjectId(), user.toJSONObject());
	}

	// 只保存好友的id
	public static void saveFriendId(String userId) {
		String id = UserService.getCurrentUserId();
		String temp = _cache.getAsString("Friend_" + id) == null ? "" : _cache
				.getAsString("Friend_" + id);
		_cache.put("Friend_" + id, temp + userId + ",");
	}

	// 删除一个好友
	public static void deletFriend(String userId) {
		String id = UserService.getCurrentUserId();
		String[] ids = _cache.getAsString("Friend_" + id).split(",");
		String isString = "";
		for (int i = 0; i < ids.length; i++) {
			if (!ids[i].equals(userId)) {
				isString += ids[i] + ",";
			}
		}
		if (isString.equals("null")) {
			_cache.put("Friend_" + id, "");
			return;

		}
		_cache.put("Friend_" + id, isString);
	}

	// 判断是否是好友
	public static boolean isFriend(String userId) {
		String id = UserService.getCurrentUserId();
		if (_cache.getAsString("Friend_" + id) != null) {
			String[] ids = _cache.getAsString("Friend_" + id).split(",");
			for (int i = 0; i < ids.length; i++) {
				if (ids[i].equals(userId)) {
					return true;
				}
			}

		}
		return false;
	}

	// 保存一个陌生人
	public static void saveStranger(MLUser user) {
		String id = UserService.getCurrentUserId();
		String temp = _cache.getAsString("Chat_" + id) == null ? "" : _cache
				.getAsString("Chat_" + id);
		_cache.put("Chat_" + id, temp + user.getObjectId() + ",");
		_cache.put(user.getObjectId(), user.toJSONObject());
	}

	// 更新本地所有联系人的信息
	public static void reloadContact() {
		String[] ids = getAllChatId();
		for (String userId : ids) {
			AVQuery<MLUser> query = new AVQuery<MLUser>("_User");
			query.getInBackground(userId, new GetCallback<MLUser>() {

				@Override
				public void done(MLUser mlUser, AVException e) {
					if (e == null) {
						if (mlUser != null) {
							_cache.put(mlUser.getObjectId(),
									mlUser.toJSONObject());
						}
					}
				}
			});
		}
	}

	// 查询所有聊过天的Id
	public static String[] getAllChatId() {
		String[] ids = _cache.getAsString(
				"Chat_" + UserService.getCurrentUserId()).split(",");
		return ids;
	}

	// 查找所有的好友id
	public static List<JSONObject> getAllFriend() {
		List<JSONObject> ChatId = new ArrayList<JSONObject>();
		if (_cache.getAsString("Friend_" + UserService.getCurrentUserId()) != null
				// && !_cache.getAsString(
				// "Friend_" + UserService.getCurrentUserId()).equals(
				// "null")
				&& !_cache.getAsString(
						"Friend_" + UserService.getCurrentUserId()).equals("")) {
			String[] ids = _cache.getAsString(
					"Friend_" + UserService.getCurrentUserId()).split(",");
			for (int i = 0; i < ids.length; i++) {
				ChatId.add(_cache.getAsJSONObject(ids[i]));
			}
		}

		return ChatId;
	}

	// 根据id得到昵称
	public static String getNickById(String Id) {
		if (Id.equals(Constant.SYSTEM)) {
			return "口袋君";
		}

		JSONObject user = _cache.getAsJSONObject(Id);
		String name = null;
		if (user == null) {
			name = "陌生人";
		} else {
			try {
				name = user.getString("nickname");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return name;
	}

	// 根据id得到头像
	public static String getAvatarById(String Id) {
		JSONObject user = _cache.getAsJSONObject(Id);
		String avatar = null;
		if (user != null) {
			try {
				avatar = user.getString("subAvatar");
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return avatar;
	}

	// 保存试聊记录
	public static void saveTestOrderUserId(String userId) {
		String id = UserService.getCurrentUserId();
		String temp = _cache.getAsString("TestOrder_" + id) == null ? ""
				: _cache.getAsString("TestOrder_" + id);
		_cache.put("TestOrder_" + id, temp + userId + ",");
	}

	// 判断是否在试聊记录中
	public static boolean isHasTestOrder(String userId) {
		String id = UserService.getCurrentUserId();
		if (_cache.getAsString("TestOrder_" + id) != null
				&& _cache.getAsString("TestOrder_" + id) != "") {
			String[] ids = _cache.getAsString("TestOrder_" + id).split(",");
			for (int i = 0; i < ids.length; i++) {
				if (ids[i].equals(userId)) {
					return true;
				}
			}

		}
		return false;

	}

	public void clearCache() {
		String id = UserService.getCurrentUserId();
		// _cache.put("Friend_" + id, "");
		// _cache.put("TestOrder_" + id, "");
		_cache.clear();
		friendMultiple = 0;
		testOrderMultiple = 0;
		LovePeopleMultiple = 0;
		LoveArticleMultiple = 0;
		isFriendOver1000 = false;
		isTestOrderOver1000 = false;
		isLoveArticleOver1000 = false;
		userIds = "";
	}

}
